package com.piece.admin.service;

import com.piece.admin.api.dto.SysUserDTO;
import com.piece.admin.model.TbSysUser;
import com.piece.admin.support.UserInfoSupport;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.constant.PatternConstants;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.dto.UserDetailDTO;
import com.piece.core.framework.util.object.BeanUtil;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * 用户登录方法
 */
@Service("userDetailService")
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private TbSysUserService tbSysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        TbSysUser user = tbSysUserService.findByLoginName(username);

        if (null == user && maybeMobile(username)) {
            user = tbSysUserService.findByMobile(username);
        }

        if (null == user && maybeEmail(username)) {
            user = tbSysUserService.findByEmail(username);
        }

        if (null == user) {
            user = tbSysUserService.findByOpenId(username);
        }

        if (null == user) {
            return null;
        }

        // 权限列表
        UserInfoSupport.setOtherInfo(user);
        String permissions = UserInfoSupport.getPermission(user.getUserId()).stream().collect(Collectors.joining(FrameWorkConstants.SPLIT_PARAM));
        UserDetailDTO detail = new UserDetailDTO(user.getUserId() + "", user.getLoginName(), user.getUserName(), user.getPassword(), user.getSalt(), Convert.toStr(user.getDeptId()), user.getDeptName(), AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
        detail.setAvatar(user.getAvatar());
        SysUserDTO sysUser = new SysUserDTO();
        BeanUtil.copyProperties(user, sysUser, true);
        detail.setDetail(sysUser);
        return detail;
    }

    private boolean maybeEmail(String username) {
        return username.matches(PatternConstants.EMAIL);
    }

    private boolean maybeMobile(String username) {
        return username.matches(PatternConstants.MOBILE);
    }
}
